package com.ruicar.afs.cloud.basic.cms.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.entity.BasicBankCard;
import com.ruicar.afs.cloud.basic.common.entity.BasicFinancialAgreement;
import com.ruicar.afs.cloud.basic.common.entity.BasicMainInfo;
import com.ruicar.afs.cloud.basic.common.entity.BasicRepaymentPlan;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.common.vo.CompanyAccountVo;
import com.ruicar.afs.cloud.basic.common.vo.ContractInfoVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.AssetTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.RepaymentStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 多品合同对接聚合层 查询合同状态
 */
@Slf4j
@RestController
@RequestMapping("/icosContract")
@AllArgsConstructor
public class IcosContractController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicBankCardService basicBankCardService;
    private final BasicFinancialAgreementService basicFinancialAgreementService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;


    @ApiOperation(value = "合同信息")
    @PostMapping("/getContract")
    public IResponse<ContractInfoVo> getContract(@RequestParam("contractNo") String contractNo){
        log.error("-------------------ccsInterface合同信息接口传入的参数为:{}-------------------",contractNo);
        if (EmptyUtils.isEmpty(contractNo)){
            return IResponse.fail("合同编号不能为空");
        }
        ContractInfoVo contractInfoVo = new ContractInfoVo();
        /**  基本信息 by ZC.GUO  **/
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,contractNo)
        );
        if (EmptyUtils.isEmpty(mainInfo)){
            log.error("-------------------ccsInterface合同信息接口未查询到任何数据mainInfo为空-------------------");
            return IResponse.fail("未找到对应合同");
        }else{
            contractInfoVo.setContractNo(mainInfo.getContractNo());
            contractInfoVo.setContractStatus(mainInfo.getContractStatus());
            contractInfoVo.setStartDate(EmptyUtils.isNotEmpty(mainInfo.getStartDate())? DateUtil.format(mainInfo.getStartDate(),"yyyyMMdd"):"");
            contractInfoVo.setLendPassDate(EmptyUtils.isNotEmpty(mainInfo.getLendPassDate())?DateUtil.format(mainInfo.getLendPassDate(),"yyyyMMdd"):"");
            contractInfoVo.setEndDate(EmptyUtils.isNotEmpty(mainInfo.getEndDate())?DateUtil.format(mainInfo.getEndDate(),"yyyyMMdd"):"");
            contractInfoVo.setLoanModel("银行代扣 Direct Debit");
            contractInfoVo.setProductName(mainInfo.getProductName());
        }
        /**  还款卡信息 by ZC.GUO  **/
        BasicBankCard bankCard = basicBankCardService.getOne(Wrappers.<BasicBankCard>query().lambda()
                .eq(BasicBankCard::getContractNo,mainInfo.getContractNo())
        );
        if (EmptyUtils.isNotEmpty(bankCard)){
            contractInfoVo.setBankBranch(bankCard.getBankBranch());
            Map<String, List<DicDataDto>> map = DicHelper.getDicMaps("bankCode");
            List<DicDataDto> list=map.get("bankCode");
            for (DicDataDto dto : list){
                if(dto.getValue().equals(bankCard.getBankCode())){
                    contractInfoVo.setBankName(dto.getTitle());
                }
            }
            contractInfoVo.setAccountName(bankCard.getAccountName());
            contractInfoVo.setAccountNo(bankCard.getAccountNo());
        }
        /**  金融信息 by ZC.GUO  **/
        BasicFinancialAgreement financialAgreement = basicFinancialAgreementService.getOne(Wrappers.<BasicFinancialAgreement>query().lambda()
                .eq(BasicFinancialAgreement::getContractNo,mainInfo.getContractNo())
                .eq(BasicFinancialAgreement::getCostType, AssetTypeEnum.CAR_AMT)
        );
        if (EmptyUtils.isNotEmpty(financialAgreement)){
            contractInfoVo.setLoanTerm(financialAgreement.getLoanTerm());
            contractInfoVo.setLoanAmt(financialAgreement.getLoanAmt());
            contractInfoVo.setDownPayAmt(financialAgreement.getDownPayAmt());
            contractInfoVo.setContractAmt(financialAgreement.getContractAmt());
            contractInfoVo.setSettleRate(financialAgreement.getSettleRate());
            contractInfoVo.setCustRate(financialAgreement.getCustRate());
            contractInfoVo.setDiscountRate(financialAgreement.getSettleRate().subtract(financialAgreement.getCustRate()));
        }
        /**  还款计划信息 by ZC.GUO  **/
        BasicRepaymentPlan repaymentPlan = basicRepaymentPlanService.calculateRepaymentInfo(basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
                .ne(BasicRepaymentPlan::getTermNo, BigDecimal.ZERO.intValue())
                .orderByAsc(BasicRepaymentPlan::getTermNo)
        ));
        if (EmptyUtils.isNotEmpty(repaymentPlan)){
            contractInfoVo.setPaidTerms(repaymentPlan.getPaidTerms());
            contractInfoVo.setTotalRent(repaymentPlan.getTotalRent());
            LambdaQueryWrapper<BasicRepaymentPlan> queryWrapper2 = new QueryWrapper<BasicRepaymentPlan>().lambda();
            queryWrapper2.eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo());
            queryWrapper2.and(wrapper -> wrapper.eq(BasicRepaymentPlan::getStatus, RepaymentStatusEnum.UNPAID).or()
                    .eq(BasicRepaymentPlan::getStatus, RepaymentStatusEnum.OVERDUE));
            int count = basicRepaymentPlanService.count(queryWrapper2);

            contractInfoVo.setTermNo(count);
            contractInfoVo.setRent(repaymentPlan.getReceivableRent());
        }

        /**  公司账户处理 by ZC.GUO  **/
        CompanyAccountVo companyAccountVo = new CompanyAccountVo();
        companyAccountVo.setBankName("");
        companyAccountVo.setCompanyBankAccount("");
        companyAccountVo.setCompanyBankBranch("");
        List<CompanyAccountVo> companyAccount = new ArrayList<>();
        companyAccount.add(companyAccountVo);
        contractInfoVo.setCompanyAccount(companyAccount);
        return IResponse.success(contractInfoVo);

    }

}
